<template>
  <div>
    <el-dialog :visible="visible" @close="closeModel">
      <template slot="title"
        ><div class="user-model-title">
          <span class="user-model-title-text">切换用户</span>
          <el-button type="primary" size="mini" @click="goCreateUser"
            >添加用户</el-button
          >
        </div>
      </template>
      <div class="user-model-body">
        <div
          class="user-model-single"
          v-for="(user, index) in userList"
          :key="index">
          <div class="user-model-body-left" @click="changeUser(user)">
            <img
              class="user-avatar"
              src="../assets/image/avatar-user-rectangle.png" />
            <div class="user-info">
              <div class="user-info-top">
                <span class="user-name">{{ user.answeUserName }}</span
                ><span class="user-phone">{{
                  user.answeUserPhone ? '手机号：' + user.answeUserPhone : ''
                }}</span>
              </div>
              <div class="user-info-bottom">
                <div
                  :class="
                    user.sex == 0 ? 'user-gender male' : 'user-gender female'
                  ">
                  <i
                    :class="
                      user.sex == 0 ? 'el-icon-male' : 'el-icon-female'
                    "></i
                  ><span class="user-gender-text">{{
                    user.sex == 0 ? ' 男' : ' 女'
                  }}</span>
                </div>
                <div class="user-info-tags default" v-if="user.isDefault">
                  默认
                </div>
                <div class="user-info-tags info" v-if="user.age">
                  {{ user.age + '岁' }}
                </div>
                <div class="user-info-tags info" v-if="user.height">
                  {{ user.height + '厘米' }}
                </div>
                <div class="user-info-tags info" v-if="user.weight">
                  {{ user.weight + '公斤' }}
                </div>
              </div>
            </div>
          </div>
          <div class="user-model-body-right">
            <img
              class="user-operation edit"
              src="../assets/image/edit-webfront.png"
              @click="goEditUser(user)" />
            <img
              class="user-operation"
              src="../assets/image/delete-webfront.png"
              @click="deleteUser(user)" />
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      class="user-edit-dialog"
      :visible="editingUser"
      @close="closeEditModel">
      <template slot="title"
        ><div class="user-model-title">
          <span class="user-model-title-text">修改用户资料</span>
        </div>
      </template>
      <div class="edit-form-wrapper">
        <el-form
          ref="editForm"
          :model="form"
          :rules="rules"
          label-position="left">
          <el-form-item class="edit-form-item" prop="relation">
            <template slot="label">
              <div class="edit-label-with-tag">
                <span>关系</span>
                <div class="require-tag">必填</div>
              </div>
            </template>
            <el-select
              class="edit-form-select"
              v-model="form.relation"
              placeholder="请选择">
              <el-option
                v-for="(item, index) in relationList"
                :key="index"
                :label="item"
                :value="index"
                >{{ item }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="edit-form-item" prop="answeUserName">
            <template slot="label">
              <div class="edit-label-with-tag">
                <span>姓名</span>
                <div class="require-tag">必填</div>
              </div>
            </template>
            <el-input
              class="edit-form-input"
              v-model="form.answeUserName"></el-input>
          </el-form-item>
          <el-form-item class="edit-form-item" prop="sex">
            <template slot="label">
              <div class="edit-label-with-tag">
                <span>性别</span>
                <div class="require-tag">必填</div>
              </div>
            </template>
            <el-radio-group v-model="form.sex">
              <el-radio :label="'0'">男</el-radio>
              <el-radio :label="'1'">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item class="edit-form-item" prop="age">
            <template slot="label">
              <div class="edit-label-with-tag">
                <span>年龄</span>
                <div class="require-tag">必填</div>
              </div>
            </template>
            <el-input
              class="edit-form-input age"
              v-model="form.age"
              type="number"
              min="0">
              <span slot="suffix" class="input-suffix-text">岁</span></el-input
            >
            <el-input
              class="edit-form-input age"
              v-model="form.month"
              v-if="form.age == 0"
              type="number"
              min="1"
              max="12">
              <span slot="suffix" class="input-suffix-text"
                >个月</span
              ></el-input
            >
          </el-form-item>
          <el-form-item class="edit-form-item" label="身高" prop="height">
            <el-input v-model="form.height">
              <span slot="suffix" class="input-suffix-text"
                >厘米</span
              ></el-input
            >
          </el-form-item>
          <el-form-item class="edit-form-item" label="体重" prop="weight">
            <el-input v-model="form.weight">
              <span slot="suffix" class="input-suffix-text"
                >千克</span
              ></el-input
            >
          </el-form-item>
        </el-form>
        <div class="bmi-wrapper">
          <div class="bmi-text">{{ '您的BMI指数为：' + bmi }}</div>
          <div class="bmi-number-wrapper">
            <span class="bmi-number-single">10</span
            ><span class="bmi-number-single">20</span
            ><span class="bmi-number-single">30</span>
          </div>
          <div class="bmi-line-wrapper">
            <div class="bmi-status-icon" :style="`left:${bmiImageLeft}px`">
              <img class="bmi-icon-img" :src="bmiImageList[bmiType]" />
            </div>
            <div class="bmi-line-single-wrapper">
              <div class="bmi-line-single type0"></div>
              <div class="bmi-line-text">偏瘦</div>
            </div>

            <div class="bmi-line-single-wrapper">
              <div class="bmi-line-single type1"></div>
              <div class="bmi-line-text">正常</div>
            </div>
            <div class="bmi-line-single-wrapper">
              <div class="bmi-line-single type2"></div>
              <div class="bmi-line-text">偏重</div>
            </div>
            <div class="bmi-line-single-wrapper">
              <div class="bmi-line-single type3"></div>
              <div class="bmi-line-text">肥胖</div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="info" plain @click="closeEditModel">取消</el-button>
        <el-button type="primary" @click="handelEdit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import request from '../utils/request'
  export default {
    name: 'UserInfoModel',
    props: {
      visible: Boolean,
      options: Object,
    },
    components: {},
    data() {
      return {
        userId: JSON.parse(localStorage.getItem('userInfo')).userId,
        editAnsweUserId: undefined,
        userList: [],
        bmiImageList: [
          require('../assets/image/bmi-1.png'),
          require('../assets/image/bmi-2.png'),
          require('../assets/image/bmi-3.png'),
          require('../assets/image/bmi-4.png'),
        ],
        bmiType: 0,
        bmiImageLeft: 14,
        editingUser: false,
        form: {
          answeUserName: '',
          sex: '',
          age: '',
          month: '',
          height: '',
          weight: '',
          relation: '',
          answeUserId: null,
        },
        bmi: 0,
        relationList: ['本人', '夫妻', '子女', '朋友', '其他'],
        rules: {
          answeUserName: [{ validator: this.validate, trigger: 'blur' }],
          sex: [{ validator: this.validate, trigger: 'change' }],
          age: [{ validator: this.validate, trigger: 'change' }],
          relation: [{ validator: this.validate, trigger: 'blur' }],
          height: [{ validator: this.validate, trigger: 'blur' }],
          weight: [{ validator: this.validate, trigger: 'blur' }],
        },
      }
    },
    computed: {},
    watch: {
      form: {
        deep: true,
        handler(n, o) {
          console.log('watch form :>> ', this, n)
          let h = n.height / 100
          let w = n.weight
          if (h && w) {
            let bmi = w / (h * h)
            console.log('bmi :>> ', bmi)
            this.bmi = bmi.toFixed(0)
          }
        },
      },
      bmi(n, o) {
        if (n < 10) {
          this.bmiType = 0
          this.bmiImageLeft = 14 + this.bmi * 5.8
        } else if (n < 20) {
          this.bmiType = 1
          this.bmiImageLeft = 104 + (this.bmi - 10) * 7.2
        } else if (n < 30) {
          this.bmiType = 2
          this.bmiImageLeft = 200 + (this.bmi - 20) * 7.2
        } else {
          this.bmiType = 3
          this.bmiImageLeft = 320
        }
      },
    },
    created() {
      console.log('create userinfo :>> ')
      this.requireUserList()
    },
    mounted() {},
    methods: {
      goEditUser(user) {
        console.log('edit/create user :>> ', user)
        this.editAnsweUserId = user.answeUserId
        this.editingUser = true
        this.requireUserInfo()
      },
      goCreateUser() {
        this.editingUser = true
      },
      changeUser(user) {
        console.log('changeUser :>> ', user)
        let params = {
          method: 'POST',
          url: '/applet/answer/user/setDefault',
          data: { answeUserId: user.answeUserId },
        }
        this.req(params).then((res) => {
          this.$message({
            message: `切换至用户“${res.data.data.answeUserName}”成功`,
            type: 'success',
          })
          setTimeout(() => {
            this.closeModel(true)
          }, 1000)
        })
      },
      deleteUser(user) {
        this.$confirm(
          '信息删除将无法恢复，确认要删除该用户信息吗？',
          '确认要删除？',
          {
            confirmButtonText: '确认删除',
            confirmButtonClass: 'confirm-button',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            this.requireDelete(user.answeUserId)
          })
          .catch(() => {})
      },
      goLogin() {
        this.$emit('goLogin')
      },

      closeModel(refresh) {
        console.log('close user model :>> ')
        this.$emit('closeModel', refresh)
      },
      closeEditModel() {
        console.log('close edit model :>> ')
        this.editingUser = false
        this.form = {
          answeUserName: '',
          sex: '',
          age: '',
          month: '',
          height: '',
          weight: '',
          relation: '',
        }
        this.editAnsweUserId = undefined
        this.requireUserList()
      },
      handelEdit() {
        this.$refs['editForm'].validate((valid) => {
          console.log('validate form :>> ', valid)
          if (valid) {
            if (this.editAnsweUserId) {
              this.requireEditUser()
            } else {
              this.requireAddUser()
            }
          }
        })
      },
      validate(rule, value, callback) {
        // this.validate = true
        console.log('rule :>> ', rule, value)
        if (rule.field == 'relation') {
          if (value === '') {
            callback(new Error('请选择关系'))
          }
        }
        if (rule.field == 'answeUserName') {
          if (value == '') {
            callback(new Error('请输入姓名'))
          }
        }
        if (rule.field == 'sex') {
          if (value == '') {
            callback(new Error('请选择性别'))
          }
        }
        if (rule.field == 'age') {
          if (value === '') {
            callback(new Error('请输入年龄'))
          } else if (value == 0) {
            console.log('this.form.month :>> ', this.form.month)
            if (!this.form.month) {
              callback(new Error('请输入月份'))
            } else if (this.form.month <= 0 || this.form.month > 12) {
              callback(new Error('请输入正确月份'))
            }
          } else if (value < 0) {
            callback(new Error('请输入正确年龄'))
          }
        }
        if (rule.field == 'height') {
          if (value !== '' && value <= 0) {
            callback(new Error('请输入正确身高'))
          }
        }
        if (rule.field == 'weight') {
          if (value !== '' && value <= 0) {
            callback(new Error('请输入正确体重'))
          }
        }
        callback()
      },
      requireDelete(answeUserId) {
        this.req({
          method: 'POST',
          url: `/applet/answer/user/delete/${answeUserId}`,
        }).then((res) => {
          console.log('delete  :>> ', res)
          this.$message({
            message: '删除成功',
            type: 'success',
          })
          this.requireUserList()
        })
      },
      requireUserInfo() {
        this.req({
          method: 'POST',
          url: `/applet/answer/user/get/${this.editAnsweUserId}`,
        }).then((res) => {
          Object.keys(this.form).forEach((k) => {
            this.form[k] = res.data.data[k]
          })
          console.log('this.form>> ', this.form)
        })
      },
      requireAddUser() {
        let data = this.form
        data.userId = this.userId
        this.req({ method: 'POST', url: '/applet/answer/user/add', data }).then(
          (res) => {
            console.log('add  res :>> ', res)
            this.$message({
              message: '添加成功',
              type: 'success',
            })
            this.closeEditModel()
          }
        )
      },
      requireEditUser() {
        let data = this.form
        data.userId = this.userId
        data.answeUserId = this.editAnsweUserId
        this.req({
          method: 'POST',
          url: '/applet/answer/user/edit',
          data,
        }).then((res) => {
          console.log('edit user post :>> ', res)
          this.$message({
            message: '编辑成功',
            type: 'success',
          })
          this.closeEditModel()
        })
      },
      requireUserList() {
        this.req({
          method: 'POST',
          url: '/applet/answer/user/list',
        }).then((res) => {
          console.log('userlist :>> ', res)
          this.userList = res.data.data
        })
      },
      req(params) {
        return new Promise((resolve, reject) => {
          request(params)
            .then((res) => {
              if (res.data.code == 200) {
                resolve(res)
              } else if (res.data.code == 401) {
                this.goLogin()
              }
            })
            .catch((err) => {
              console.log('catch error user info:>> ', err)
              if (err == 401) {
                this.goLogin()
              }
              // this.goLogin()
            })
        })
      },
    },
  }
</script>
<style scoped lang="less">
  .user-model-title {
    display: flex;
    align-items: center;
    .user-model-title-text {
      margin-right: 12px;
    }
  }
  .user-model-body {
    display: flex;
    flex-direction: column;
    max-height: 400px;
    overflow: auto;
  }
  .user-model-single {
    display: flex;
    background: #fafafa;
    margin-bottom: 16px;
    align-items: center;
    justify-content: space-between;
    border-radius: 8px 8px 8px 8px;
    padding: 0px 16px;
    .user-model-body-left {
      display: flex;
      align-items: center;
      .user-avatar {
        height: 46px;
        width: 46px;
        border-radius: 23px;
      }
      .user-info {
        display: flex;
        flex-direction: column;
        margin-left: 8px;
        height: 74px;
        width: 100%;
        justify-content: center;
        .user-info-top {
          display: flex;
          margin-bottom: 5px;
          .user-name {
            font-size: 16px;
            color: #1a1a1a;
            line-height: 19px;
            margin-right: 10px;
          }
          .user-phone {
            font-size: 12px;
            color: #999999;
            line-height: 14px;
          }
        }
        .user-info-bottom {
          display: flex;
          .user-gender {
            height: 19px;
            border-radius: 12px 12px 12px 12px;
            color: #fff;
            margin-right: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            line-height: 14px;
            padding: 1px 6px;
            &.male {
              background: #5193f7;
            }
            &.female {
              background: #f367b2;
            }
            .user-gender-text {
              padding-left: 4px;
            }
          }
          .user-info-tags {
            height: 19px;
            border-radius: 12px 12px 12px 12px;
            font-size: 12px;
            padding: 1px 6px;
            margin-right: 8px;
            &.default {
              background: rgba(253, 176, 87, 0.15);
              color: #fdb057;
            }
            &.info {
              color: #65b0b4;
              background: rgba(101, 176, 180, 0.15);
            }
          }
        }
      }
    }
    .user-model-body-right {
      .user-operation {
        height: 24px;
        width: 24px;
        &.edit {
          margin-right: 8px;
        }
      }
    }
  }
  .confirm-button {
    background-color: #ed7272 !important;
  }
  .edit-form-wrapper {
    display: flex;
    flex-direction: column;
  }
  .edit-form-item {
    display: flex;
  }
  .edit-label-with-tag {
    display: flex;
    align-items: center;

    .require-tag {
      height: 17px;
      background: rgba(237, 114, 114, 0.15);
      border-radius: 12px 12px 12px 12px;
      font-size: 12px;
      line-height: 14px;
      color: #ed7272;
      padding: 1px 6px;
      margin-left: 4px;
    }
  }
  .edit-form-select {
    width: 100%;
  }
  .edit-form-input {
    &.age {
      width: 40%;
      margin-right: 8px;
    }
  }
  .input-suffix-text {
    font-size: 14px;
    margin-right: 8px;
    color: #999;
  }
  .bmi-wrapper {
    display: flex;
    flex-direction: column;
    .bmi-text {
      font-size: 15px;
      font-weight: 400;
      color: #1a1a1a;
      line-height: 18px;
    }
    .bmi-line-wrapper {
      display: flex;
      justify-content: space-between;
      .bmi-status-icon {
        position: absolute;
        margin-top: -4px;
        .bmi-icon-img {
          height: 28px;
          width: 28px;
        }
      }
      .bmi-line-single-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .bmi-line-single {
        width: 72px;
        height: 16px;
        border-radius: 10px 10px 10px 10px;
      }
      .bmi-line-text {
        color: #999;
        font-size: 12px;
        margin-top: 6px;
      }
      .bmi-line-single.type0 {
        background: #5193f6;
      }

      .bmi-line-single.type1 {
        background: #65b0b4;
      }

      .bmi-line-single.type2 {
        background: #fdb057;
      }

      .bmi-line-single.type3 {
        background: #ed7272;
      }
    }
    .bmi-number-wrapper {
      margin-top: 14px;
      display: flex;
      justify-content: space-around;
      .bmi-number-single:first-child {
        padding-left: 35px;
      }
      .bmi-number-single:nth-child(3) {
        padding-right: 35px;
      }
    }
  }

  /deep/ .el-dialog {
    width: 528px;
    background: #ffffff;
    border-radius: 16px 16px 16px 16px;
  }
  // /deep/ .el-form-item {
  //   display: flex;
  // }
  /deep/ .user-edit-dialog .el-dialog {
    width: 394px;
  }
  /deep/ .el-form-item__label {
    width: 30%;
  }
  /deep/ .el-form-item__content {
    width: 70%;
  }
</style>
